const app = getApp()

import {
  myRequesy
} from '../../request/api.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight, //获取高度
    applyObj: null, //保存活动详情携带的参数
    titleValue: '', //获取用户输入标题的值
    textValue: '', //获取用户输入简介的值
    UploadList: [], //保存上传的图片链接数组
    nameValue: '', //获取用户输入姓名的值
    phoneNumber: '', //获取用户手机号,
    schoolValue: '' //获取用户输入学校或职业的值
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    let that = this
    that.setData({
      applyObj: options, //用户封面
      applyId: options.id, //活动id
      status: parseInt(options.status), //判断请求是否是修改
      statusEnd: options.end ? JSON.parse(options.end) : '', //判断请求是否是修改
    })
    this.getUserInfo()
    this.getRedactList()


    // 获取手机号
    wx.login({
      success(res) {
        if (res.errMsg === "login:ok") {
          that.setData({
            codeLogin: res.code
          })
        }
      }
    })
  },


  //预览图片回调
  headlepreImg(e) {
    if (!this.data.statusEnd) {
      let {
        UploadList
      } = this.data
      let current = e.currentTarget.dataset.img
      wx.previewImage({
        current,
        urls: UploadList
      })
      return
    }

  },


  // 获取用户手机号回调
  getPhoneNumber(e) {
    let that = this
    console.log(e);
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      myRequesy({
        url: 'user/phone',
        method: 'POST',
        data: {
          code: this.data.codeLogin,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        },
      }).then(res => {
        if (res.data.code === 0) {
          that.setData({
            phoneNumber: res.data.data.phoneNumber
          })
        }
      })
      // wx.login({
      //   success(res) {
      //     console.log(res);
      //   }
      // })
    } else {
      wx.showToast({
        title: '请授权手机号',
        icon: 'none'
      })
    }



  },


  // 获取用户收货地址回调
  // headleAddress() {
  //   wx.chooseAddress({
  //     success: (result) => {
  //       console.log(result);
  //       let regisinfo = {
  //         receiveAddr: result.provinceName + result.cityName + result.countyName + result.detailInfo,
  //         receiveName: result.userName,
  //         receivePhone: result.telNumber,
  //       }
  //       this.setData({
  //         regisinfo
  //       })
  //     },
  //   })
  // },

  //跳转回活动详情页
  headleDack() {
    wx.navigateBack({
      delta: 1,
    })
  },



  // 获取报名用户基本信息
  getUserInfo() {
    let that = this
    myRequesy({
      url: 'user/info'
    }).then(res => {
      if (res.data.code === 0) {
        that.setData({
          userInfo: res.data.data
        })
      }
    })
  },

  // 用户标题
  headleTitle(e) {
    if (this.data.titleValue.length < 10) {
      this.setData({
        titleValue: e.detail.value
      })
      return
    }


  },

  // 用户简介文本域
  headleAreaValue(e) {
    this.setData({
      textValue: e.detail.value
    })


    console.log(e.detail.value);
  },

  //上传照片回调
  headleUpload() {
    let index = 0
    let that = this
    wx.chooseImage({
      count: that.data.status === 3 ? 1 : 9 - that.data.UploadList.length,
      sizeType: that.data.status === 3 ? ['original', 'compressed'] : ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        let tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '正在上传...',
          icon: 'loading',
          mask: true
        })
        tempFilePaths.forEach((item, i) => {
          let tempPaths = item
          let fileNames = tempPaths.lastIndexOf("."); //取到文件名开始到最后一个点的长度
          let fileNameLength = tempPaths.length; //取到文件名长度
          let fileFormat = tempPaths.substring(fileNames + 1, fileNameLength); //截
          if (fileFormat === "jpg" || fileFormat === "png" || fileFormat === "jpeg") {
            wx.uploadFile({
              filePath: item,
              name: 'imgFile',
              url: app.globalData.UpUrl + (that.data.status === 3 ? 'upload-bigimg' : 'upload-img'),
              header: {
                'content-type': 'multipart/form-data',
                'Authorization': wx.getStorageSync('userInfo').token
              },
              success(res) {
                index++
                let data = JSON.parse(res.data)
                if (data.code === 0) {
                  let UploadList = that.data.UploadList
                  UploadList.push(data.data.imgUrl)
                  that.setData({
                    UploadList
                  })
                } else if (data.code === 3015 || data.code === 3016) {
                  wx.showToast({
                    title: '不能包含敏感图片',
                    icon: "none"
                  })
                }
                if (tempFilePaths.length === index) {
                  wx.hideLoading()
                }
              },
            })
          } else {
            wx.showToast({
              title: '文件格式错误',
              icon: "none"
            })
          }
        })
      }
    })
  },

  //移除对应的图片
  headleDelete(e) {
    let index = e.currentTarget.dataset.index
    let UploadList = this.data.UploadList
    UploadList.splice(index, 1)
    this.setData({
      UploadList
    })
  },

  //获取用户输入的姓名
  headleName(e) {
    this.setData({
      nameValue: e.detail.value
    })
  },



  //用户学校或职业
  headleSchool(e) {
    if (this.data.schoolValue.length < 10) {
      this.setData({
        schoolValue: e.detail.value
      })
      return
    }
  },

  // 提交报名回调
  headleSubmit() {
    let {
      applyObj,
      textValue,
      UploadList,
      nameValue,
      phoneNumber,
      schoolValue,
      titleValue
    } = this.data

    if (!textValue.trim() || !titleValue.trim() || !nameValue.trim() || !schoolValue.trim() || phoneNumber === '' || UploadList.length < 1) {
      wx.showToast({
        title: '所有选项都是必填项',
        icon: 'none',
        mask: true
      })
      return
    }
    if (nameValue.length < 2) {
      wx.showToast({
        title: '请输入正确的姓名',
        icon: 'none'
      })
      return
    }
    let that = this
    wx.requestSubscribeMessage({
      tmplIds: ['iXO6nRRt8g0Op1YQg9gs7WfytX9-vj8O3ml3sqjx7z0', '8pUorSTDgk0nqAU7v6GxRM3LP2RY_EmDgcrimSx1X0Q', 'Ke1p0Jn84Q_5XVYM6TT5aWb1Z4-oy7bJ2odnnH88kOE'],
      success(res) {
        myRequesy({
          url: that.data.status === 1 ? 'activity/sign' : that.data.status === 2 ? 'sign/update' : that.data.status === 3 ? 'big-activity/sign' : 'big-sign/update',
          method: 'POST',
          data: {
            tag_id: applyObj.tagId,
            dynamic_id: that.data.dynamic_id,
            content: textValue,
            img_list: UploadList,
            realName: nameValue,
            phoneNum: phoneNumber,
            title: titleValue,
            school: schoolValue,
            fid: applyObj.fid
          }
        }).then(res => {
          if (res.data.code === 0) {
            if (that.data.status === 3) {
              wx.navigateBack({
                delta: 0,
                success() {
                  let data = encodeURIComponent(that.data.applyObj.web_view) //编码
                  wx.navigateTo({
                    url: '/pages/webView/webView?url=' + data,
                  })
                }
              })

            } else {
              wx.reLaunch({
                url: '/pages/record/record',
              })
            }

          } else if (res.data.code === 3015 || res.data.code === 3016) {
            wx.showToast({
              title: '不能包含铭内容',
              icon: "none"
            })
          } else if (res.data.code === 3010) {
            wx.showToast({
              title: '当前已报名或手机号重复',
              icon: 'none'
            })
          }

        })
      }
    })
  },
  // 点击取消返回上一页
  navCancel() {
    wx.navigateBack({
      delta: 1,
    })
  },
  // 根据编辑或查看跳转携带的id获取数据
  getRedactList() {
    let that = this
    myRequesy({
      url: that.data.status === 4 ? 'big-sign/detail' : 'sign/detail',
      data: {
        dynamic_id: that.data.applyId
      }
    }).then(res => {
      if (res.data.code === 0) {
        that.setData({
          applyObj: res.data.data,
          UploadList: res.data.data.img_list,
          textValue: res.data.data.content,
          nameValue: res.data.data.regisinfo.realName,
          phoneNumber: res.data.data.regisinfo.phoneNum,
          titleValue: res.data.data.regisinfo.title,
          schoolValue: res.data.data.regisinfo.school,
          dynamic_id: res.data.data.id
        })
      }

    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


})